var express = require('express');
var router = express.Router();
var { customQuery } = require('../mysql/index')

// 查询 mysql表 learn_class , 获取数据get请求 /
router.get('/', function (req, res, next) {
    // Extract 'type', 'limit', 'page', and 'key' from the request query
    const { type, limit = 10, page = 1, key } = req.query;
    // Construct the SQL query
    let sql = `SELECT * FROM learn_class`;
    if (type) {
        sql += ` WHERE type = '${type}'`;
    }
    if (key) {
        sql += ` AND (name LIKE '%${key}%' OR description LIKE '%${key}%')`;
    }
    sql += ` LIMIT ${limit} OFFSET ${(page - 1) * limit}`;
    // Execute the query
    customQuery(sql).then(results => {
        // Construct the SQL query to get total count
        let countSql = `SELECT COUNT(*) as total FROM learn_class`;
        if (type) {
            countSql += ` WHERE type = '${type}'`;
        }
        if (key) {
            countSql += ` AND (name LIKE '%${key}%' OR description LIKE '%${key}%')`;
        }
        const learnMorePromises = results.map(result => {
            const learnMoreIds = result.learn_more || [];
            const caseListIds = result.case_list || [];
            let arr = []
            if (result.learn_more) {
                const learnMoreQuery = `SELECT * FROM link WHERE id IN (${result.learn_more})`;
                const learnMorePromise = customQuery(learnMoreQuery);
                arr.push(learnMorePromise)
            }
            if (result.case_list) {
                const caseListQuery = `SELECT * FROM link WHERE id IN (${result.case_list})`;
                const caseListPromise = customQuery(caseListQuery);
                arr.push(caseListPromise)
            }
            if(arr.length){
                return Promise.all(arr)
                .then(([learnMoreResults, caseListResults]) => {
                    result.learn_more = learnMoreResults;
                    result.case_list = caseListResults;
                    console.log('learnMoreResults', learnMoreResults);
                    console.log('caseListResults', caseListResults);
                });
            }
        });
        console.log(22222222222222222);
        // Wait for all link data queries to finish
        Promise.all(learnMorePromises)
            .then(() => {
                console.log(333333333333333333333);
                // Construct the SQL query to get total count
                let countSql = `SELECT COUNT(*) as total FROM learn_class`;
                if (type) {
                    countSql += ` WHERE type = '${type}'`;
                }
                if (key) {
                    countSql += ` AND (name LIKE '%${key}%' OR description LIKE '%${key}%')`;
                }
                // Execute the count query
                customQuery(countSql).then(countResults => {
                    return res.status(200).send({ code: 200, msg: '数据获取成功', data: { list: results, total: countResults[0].total } });
                });
            });
    })
});

// 新增数据 post请求 add 字段 name, type, description, sort, case_list, learn_more
router.post('/add', function (req, res, next) {
    // Extract fields from the request body
    const { name, type, description, sort, case_list = '', learn_more = '' } = req.body;
    // Construct the SQL query
    const sql = `INSERT INTO learn_class (name, type, description, sort, case_list, learn_more) VALUES ('${name}', '${type}', '${description}', '${sort}', '${case_list}', '${learn_more}')`;
    // Execute the query
    customQuery(sql).then(results => {
        return res.status(200).send({ code: 200, msg: '数据添加成功', list: results });
    })
});

// 修改数据 post请求 update 字段 name, type, description, sort, case_list, learn_more
router.post('/update', function (req, res, next) {
    // Extract fields from the request body
    const { id, name, type, description, sort, case_list, learn_more } = req.body;
    // Construct the SQL query
    const sql = `UPDATE learn_class SET name = '${name}', type = '${type}', description = '${description}', sort = '${sort}', case_list = '${case_list}', learn_more = '${learn_more}' WHERE id = ${id}`;
    // Execute the query
    customQuery(sql).then(results => {
        return res.status(200).send({ code: 200, msg: '数据更新成功', list: results });
    })
});

// 根据传入的id删除数据  post请求  delete
router.post('/delete', function (req, res, next) {
    // Extract 'id' from the request body
    const { id } = req.body;

    // Construct the SQL query
    const sql = `DELETE FROM learn_class WHERE id = ${id}`;

    // Execute the query
    customQuery(sql).then(results => {
        return res.status(200).send({ code: 200, msg: '数据删除成功', list: results });
    })
});



module.exports = router;



